What is @cloudflare/workers-types?
@cloudflare/workers-types provides TypeScript type definitions for Cloudflare Workers, enabling developers to write type-safe code for Cloudflare's serverless platform.
What are @cloudflare/workers-types's main functionalities?
FetchEvent
The FetchEvent interface represents the event that is fired when a Fetch request is made. This allows you to intercept and handle HTTP requests.
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request: Request): Promise<Response> {
return new Response('Hello, world!');
}
KVNamespace
KVNamespace provides type definitions for Cloudflare Workers KV, a key-value storage system. This allows you to interact with KV storage in a type-safe manner.
declare const MY_KV_NAMESPACE: KVNamespace;
async function handleRequest(request: Request): Promise<Response> {
const value = await MY_KV_NAMESPACE.get('my-key');
return new Response(value || 'Key not found');
}
DurableObjectNamespace
DurableObjectNamespace provides type definitions for Durable Objects, which are stateful objects that can be used to manage state across multiple requests.
declare const MY_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;
class MyDurableObject {
state: DurableObjectState;
constructor(state: DurableObjectState) {
this.state = state;
}
async fetch(request: Request): Promise<Response> {
return new Response('Durable Object response');
}
}
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request: Request): Promise<Response> {
const id = MY_DURABLE_OBJECT_NAMESPACE.idFromName('object-name');
const stub = MY_DURABLE_OBJECT_NAMESPACE.get(id);
return stub.fetch(request);
}
Other packages similar to @cloudflare/workers-types
@types/aws-lambda
@types/aws-lambda provides TypeScript type definitions for AWS Lambda, another serverless computing platform. While it offers type safety for AWS Lambda functions, it does not cover Cloudflare-specific features.
@types/express
@types/express provides TypeScript type definitions for Express.js, a web application framework for Node.js. While it helps in building server-side applications, it does not offer the serverless and edge computing capabilities of Cloudflare Workers.
Cloudflare Workers Types
Install
npm install @cloudflare/workers-types
-- Or
yarn add @cloudflare/workers-types
Usage
The following is a minimal tsconfig.json
for use alongside this package:
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"lib": ["ES2020", "WebWorker"],
"types": ["@cloudflare/workers-types"]
}
}
Using bindings
It's recommended that you create an ambient type file for any bindings your Worker uses. Create a file named bindings.d.ts
in your src directory:
bindings.d.ts
export {};
declare global {
const MY_ENV_VAR: string
const MY_SECRET: string
const myKVNamespace: KVNamespace
}